# uncompyle6 version 3.2.3
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.6.8 |Anaconda custom (64-bit)| (default, Feb 21 2019, 18:30:04) [MSC v.1916 64 bit (AMD64)]
# Embedded file name: site-packages\sqlalchemy\dialects\sybase\pysybase.py
"""
.. dialect:: sybase+pysybase
    :name: Python-Sybase
    :dbapi: Sybase
    :connectstring: sybase+pysybase://<username>:<password>@<dsn>/[database name]
    :url: http://python-sybase.sourceforge.net/

Unicode Support
---------------

The python-sybase driver does not appear to support non-ASCII strings of any
kind at this time.

"""
from sqlalchemy import types as sqltypes, processors
from sqlalchemy.dialects.sybase.base import (
    SybaseDialect,
    SybaseExecutionContext,
    SybaseSQLCompiler,
)


class _SybNumeric(sqltypes.Numeric):
    def result_processor(self, dialect, type_):
        if not self.asdecimal:
            return processors.to_float
        else:
            return sqltypes.Numeric.result_processor(self, dialect, type_)


class SybaseExecutionContext_pysybase(SybaseExecutionContext):
    def set_ddl_autocommit(self, dbapi_connection, value):
        if value:
            dbapi_connection.commit()

    def pre_exec(self):
        SybaseExecutionContext.pre_exec(self)
        for param in self.parameters:
            for key in list(param):
                param["@" + key] = param[key]
                del param[key]


class SybaseSQLCompiler_pysybase(SybaseSQLCompiler):
    def bindparam_string(self, name, **kw):
        return "@" + name


class SybaseDialect_pysybase(SybaseDialect):
    driver = "pysybase"
    execution_ctx_cls = SybaseExecutionContext_pysybase
    statement_compiler = SybaseSQLCompiler_pysybase
    colspecs = {sqltypes.Numeric: _SybNumeric, sqltypes.Float: sqltypes.Float}

    @classmethod
    def dbapi(cls):
        import Sybase

        return Sybase

    def create_connect_args(self, url):
        opts = url.translate_connect_args(username="user", password="passwd")
        return ([opts.pop("host")], opts)

    def do_executemany(self, cursor, statement, parameters, context=None):
        for param in parameters:
            cursor.execute(statement, param)

    def _get_server_version_info(self, connection):
        vers = connection.scalar("select @@version_number")
        return (vers / 1000, vers % 1000 / 100, vers % 100 / 10, vers % 10)

    def is_disconnect(self, e, connection, cursor):
        if isinstance(e, (self.dbapi.OperationalError, self.dbapi.ProgrammingError)):
            msg = str(e)
            return (
                "Unable to complete network request to host" in msg
                or "Invalid connection state" in msg
                or "Invalid cursor state" in msg
            )
        else:
            return False


dialect = SybaseDialect_pysybase
